import api from '../../config/settings'
Page({
    data: {
        backFront: true,
        record: []
    },
    switchCamera(e) {
        var old = this.data.backFront
        this.setData({
            backFront: !old
        })
    },
    onUploadPhotoSuccess(path, response) {
        // 5 上传成功，后端返回数据
        console.log(response.data)
        let resdata = JSON.parse(response.data)
        if (resdata.code != 100 && resdata.code != 102) {
            wx.showToast({
                title: '请正常拍照'
            })
            return
        }
        resdata.avatar = path
        var oldRecord = this.data.record
        oldRecord.unshift(resdata)
        console.log(oldRecord)
        this.setData({
            record: oldRecord
        })
    },
    onTakePhoto(res) {
        //3 res中会有拍摄的照片
        // 4 把照片传到后端
        wx.uploadFile({
            url: api.face,
            filePath: res.tempImagePath,
            name: 'avatar',
            success: (response) => {
                // 5 上传成功，后端返回数据
                this.onUploadPhotoSuccess(res.tempImagePath, response)
            },
            complete: function () {
                wx.hideLoading()
            }
        })
    },
    takePhoto(e) {
        // 1 打开loading
        wx.showLoading({
            title: '检测中',
            mask: true
        })
        //2 拿到相机对象，拍照
        const ctx = wx.createCameraContext()
        ctx.takePhoto({
            quality: 'high',
            success: (res) => {
                this.onTakePhoto(res)
            },
            fail: () => {
                // 拍照失败，隐藏加载提示
                wx.hideLoading();
                wx.showToast({
                    title: '拍照失败，请重试',
                    icon: 'none'
                });
            }
        })
    }
})